package com.woniu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.exception.RebornException;
import com.woniu.exception.account.AccountException;
import com.woniu.exception.account.AccountExceptionCode;
import com.woniu.exception.order.OrderException;
import com.woniu.exception.order.OrderExceptionCode;
import com.woniu.model.Result;
import com.woniu.order.client.*;
import com.woniu.order.cliententity.entity.*;
import com.woniu.order.cliententity.form.AddCredibilityForm;
import com.woniu.order.cliententity.form.AddHandelForm;
import com.woniu.order.cliententity.form.FindByLocationAndJunkForm;
import com.woniu.order.mapper.TDownpaymentMapper;
import com.woniu.order.mapper.TOrderMapper;
import com.woniu.order.mapper.TVisitMapper;
import com.woniu.order.model.TDownpayment;
import com.woniu.order.model.TOrder;
import com.woniu.order.model.TVisit;
import com.woniu.order.param.*;
import com.woniu.order.service.TOrderService;
import com.woniu.order.util.Alpay;
import com.woniu.order.util.DateUtil;
import com.woniu.order.util.GaudMapUtil;
import io.seata.spring.annotation.GlobalTransactional;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.context.Theme;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private DepotClient depotClient;

    @Autowired
    private StationClient stationClient;

    @Autowired
    private EmployeeClient employeeClient;

    @Resource
    private TOrderMapper tOrderMapper;

    @Resource
    private TVisitMapper tVisitMapper;

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private FlowClient flowClient;

    @Resource
    private Alpay alipay;

    @Resource
    private TDownpaymentMapper downpaymentMapper;

    /**
     * 新增预约上门收废品
     * @param userId 登录id
     * @param toBean 新增预约对象
     * @return
     */
    @Override
    public TOrder insetOrder(Integer  userId,AddBookingOrderParam toBean) {
        //判断用户是否存在
        Result<TUser> tUserResult = userClient.userById(userId.longValue());
        if (tUserResult.getCode()!=200){
            throw new AccountException(tUserResult.getCode(),tUserResult.getMessage());
        }
        //验证实名状态
        if (tUserResult.getData().getRealNameState()==null){
            throw new AccountException(AccountExceptionCode.ACCOUNT_NOT_ID);
        }
        //判断用户信誉分

        //判断用户地址合法性
        Long aLong = Long.valueOf(toBean.getAddressId());
        Result<UserAddrees> addressResult = userClient.addressById(aLong.longValue());
        if (addressResult.getCode()!=200){
            throw new AccountException(addressResult.getCode(),addressResult.getMessage());
        }
        if (addressResult.getData().getState()!=0){
            throw new AccountException(AccountExceptionCode.ACCOUNT_NO_ACCOUNT_NO_ADDRESS);
        }
        //判断预约时间是否合适
        Date date = new Date();
        long time = date.getTime();
        long time1 = DateUtil.stringConversionDate(toBean.getBookingTime()).getTime();
        if (time1<time){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_ACCOUNT);
        }
        //地理/逆地理编码
        Map lonAndLat = GaudMapUtil.getLonAndLat(addressResult.getData().getUserAddress(),"727abe621f3273de0e8a4b0a8fa8b3be");
        //经度
        String lng = lonAndLat.get("lng").toString();
        //维度
        String lat = lonAndLat.get("lat").toString();
        //判断废品类别是否存在返回最近站点
        Set<Integer> ids = toBean.getTypeId().stream().collect(Collectors.toSet());
        System.out.println(LocalDateTime.now());
        System.out.println(DateUtil.stringConversionLocalDate(toBean.getBookingTime()));
        System.out.println("=====================================");
        FindByLocationAndJunkForm junkForm = new FindByLocationAndJunkForm(ids, Double.valueOf(lng), Double.valueOf(lat), toBean.getBookingTime());
        Result<Station> junk = stationClient.findByLocationAndJunk(junkForm);
        System.out.println(JSONUtil.toJsonStr(junk));
        if (junk.getCode()!=200){
            throw new AccountException(junk.getCode(),junk.getMessage());
        }

        //查询订单
        TOrder tOrder1 = tOrderMapper.selectById(toBean.getOrderNum());

        //修改新订单空数据
        TOrder tOrder = BeanUtil.copyProperties(tOrder1, TOrder.class);
        tOrder.setState((long)1);
        tOrder.setUserId((long)userId);
        tOrder.setCreateTime(LocalDateTime.now().toString());
        tOrder.setBookingTime(DateUtil.stringConversionLocalDate(toBean.getBookingTime()).toString());
        tOrder.setAddress(addressResult.getData().getUserAddress());
        tOrder.setName(addressResult.getData().getUserAddress());
        tOrder.setStationId(junk.getData().getId().longValue());
        tOrderMapper.updateById(tOrder);

        //根据站点查询站长
//        employeeClient.
        //client新增 订单流程  1已下单
        AddHandelForm addHandelForm = new AddHandelForm(1, 1, userId, toBean.getOrderNum(), null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
        return tOrder;
    }

    /**
     * 站点分配员工
     * @param toBean 订单编号 员工id
     * @return 返回订单
     */
    @Override
    public TOrder assignmentEmployee(AssignmentEmployeeParam toBean) {
        //查询员工是否存在
//        employeeClient
        TOrder tOrder = tOrderMapper.selectById(toBean.getOrderNum());
        if (tOrder==null){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_NO_ORDER);
        }
        //新增流程执行

        //2024.6.15注: 更新流程后,下一步直接变成了员工确认
        AddHandelForm addHandelForm = new AddHandelForm(null, 4, Integer.parseInt(toBean.getEmployeeId()), toBean.getOrderNum(), null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        System.out.println(JSONUtil.toJsonStr(add));
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
        tOrder.setEmployId(Long.valueOf(toBean.getEmployeeId()));
        tOrder.setState((long)4);
        tOrderMapper.updateById(tOrder);
        return tOrder;
    }
    /**
     * 员工出发
     * @param orderNum 订单编号
     * @param userId 员工id
     * @return
     */
    @Override
    public TOrder employeeGo(String orderNum, Integer userId) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("id",orderNum);
        TOrder tOrder = tOrderMapper.selectOne(wrapper);
        if (tOrder==null){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_NO_ORDER);
        }
        tOrder.setEmployId(userId.longValue());
        tOrderMapper.updateById(tOrder);
        //新增流程执行
        AddHandelForm addHandelForm = new AddHandelForm(null, 3, userId, orderNum, null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
        return tOrder;
    }


    public void test(String orderNum) throws AlipayApiException {
        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();

        // 设置订单支付时传入的商户订单号
        model.setOutTradeNo(orderNum);

        // 设置查询选项
        List<String> queryOptions = new ArrayList<String>();
        queryOptions.add("trade_settle_info");
        model.setQueryOptions(queryOptions);

        // 设置支付宝交易号
        model.setTradeNo("2088721033216571 ");

        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            System.out.println("调用成功");

        } else {
            System.out.println("调用失败");

            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
    }
    /**
     * 用户确认订单
     * @param userId 用户id
     * @param orderNum 订单编号
     * @return
     */
    @Override
    public TOrder userQueryOrder(Integer userId,String orderNum) {
        System.out.println(userId);
        TOrder tOrder = tOrderMapper.selectById(orderNum);
        if (tOrder.getUserId()!=userId.longValue()){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_NO_ORDER);
        }
        //client 流程下一步
        AddHandelForm addHandelForm = new AddHandelForm(null, 7, userId, orderNum, null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
        //修改订单状态
        tOrder.setState((long)6);
        tOrderMapper.updateById(tOrder);
        //client生成审核表
        Result<?> add1 = depotClient.add(orderNum);
        if (add1.getCode()!=200){
            throw new OrderException(add1.getCode(),add1.getMessage());
        }
        return tOrder;
    }
    /**
     * 用户取消订单
     * @param userId 用户id
     * @param orderNum 订单编号
     * @return
     */
    @Override
    public TOrder cancelOrder(Integer userId,Integer accountId, String orderNum) {
        TOrder tOrder = tOrderMapper.selectById(orderNum);
        if (tOrder.getUserId()!=accountId.longValue()){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_NO_ORDER);
        }

        //client获取流程最新执行流程 判断执行到哪步
        Result<FlowHandle> flowHandleResult = flowClient.locationConfirm(orderNum);
        if(flowHandleResult.getCode()!=200){
            throw new OrderException(flowHandleResult.getCode(),flowHandleResult.getMessage());
        }
        //判断员工是否出发到站长确认
        if (flowHandleResult.getData().getFlowModeId()>2||flowHandleResult.getData().getFlowModeId()<7){
            //用户扣信誉分
            AddCredibilityForm credibilityForm = new AddCredibilityForm(userId.longValue(), (long) -10);
            Result<TUser> tUserResult = userClient.addCredibility(credibilityForm);
            if (tUserResult.getCode()!=200){
                throw new AccountException(tUserResult.getCode(),tUserResult.getMessage());
            }
        }
        //新增最新流程
        AddHandelForm addHandelForm = new AddHandelForm(null, 10, userId, orderNum, null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
        //修改订单状态
        tOrder.setState((long)10);
        //查询用户
        Result<TUser> tUserResult = userClient.byAliPayUsername(userId.longValue());
        if (tUserResult.getCode()!=200){
            throw new OrderException(tUserResult.getCode(),tUserResult.getMessage());
        }
        System.out.println(JSONUtil.toJsonStr(tUserResult.getData()));
//        //生成回访信息
//        TVisit tVisit = new TVisit();
//        tVisit.setUserPhone(tUserResult.getData().getPhone());
//        tVisit.setCreateTime(LocalDateTime.now());
//        tVisit.setVisitState(0);
//        tVisit.setOrderNum(orderNum);
//        tVisit.setStationId(tOrder.getStationId().intValue());
//        tVisitMapper.insert(tVisit);


        return tOrder;
    }
    /**
     * 用户拒绝订单
     * @param userId 用户id
     * @param orderNum 订单编号
     * @return
     */
    @Override
    public TOrder refuseOrder(Integer userId, String orderNum) {
        TOrder tOrder = tOrderMapper.selectById(orderNum);
        if (tOrder.getUserId()!=userId.longValue()){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_NO_ORDER);
        }

        //用户扣信誉分
        AddCredibilityForm credibilityForm = new AddCredibilityForm(userId.longValue(), (long) -10);
        Result<TUser> tUserResult = userClient.addCredibility(credibilityForm);
        if (tUserResult.getCode()!=200){
            throw new AccountException(tUserResult.getCode(),tUserResult.getMessage());
        }
        //client 流程下一步
        AddHandelForm addHandelForm = new AddHandelForm(null, 10, userId, orderNum, null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
//        //生成回访信息
//        TVisit tVisit = new TVisit(null, tUserResult.getData().getPhone(), LocalDateTime.now(), null, 0, orderNum, null,tOrder.getStationId().intValue());
//        tVisitMapper.insert(tVisit);
        //修改订单状态
        tOrder.setState((long) 10);
        tOrderMapper.updateById(tOrder);
        return tOrder;
    }
    /**
     * 站点通过
     * @param orderNum 订单编号
     * @param userId 站长id
     * @return
     */
    @Override
    public TOrder siteQuery(Integer userId, String orderNum) {
        //获取员工对象
        Result<Employee> employeeResult = employeeClient.byId(userId);
        if (employeeResult.getCode()!=200){
            throw new OrderException(employeeResult.getCode(),employeeResult.getMessage());
        }
        //获取订单
        TOrder tOrder = tOrderMapper.selectById(orderNum);

        //判断员工与订单是否在同一个站点
        if (tOrder.getStationId()!=employeeResult.getData().getStationId()){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_NO_ORDER);
        }
        //client同生成下个执行信息
        //client 流程下一步 7待支付
        AddHandelForm addHandelForm = new AddHandelForm(null, 7, userId, orderNum, null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
        //订单修改状态
        tOrder.setState((long)7);
        tOrderMapper.updateById(tOrder);

        return tOrder;
    }
    /**
     * 站点拒绝通过
     * @param orderNum 订单编号
     * @param userId 站长id
     * @return
     */
    @Override
    public TOrder refuseQuery(Integer userId, String orderNum) {
        //获取员工对象
        Result<Employee> employeeResult = employeeClient.byId(userId);
        if (employeeResult.getCode()!=200){
            throw new OrderException(employeeResult.getCode(),employeeResult.getMessage());
        }
        //获取订单
        TOrder tOrder = tOrderMapper.selectById(orderNum);

        //判断员工与订单是否在同一个站点
        if (tOrder.getStationId()!=employeeResult.getData().getStationId()){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_NO_ORDER);
        }
        //client同生成下个执行信息 4待骑手确认
        AddHandelForm addHandelForm = new AddHandelForm(1, 4, userId, orderNum, null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
        //订单修改状态
        tOrder.setState((long)4);
        tOrderMapper.updateById(tOrder);

        return tOrder;
    }
    /**
     *员工返程
     * @param orderNum 订单编号
     * @param userId 员工id
     * @return
     */
    @Override
    public TOrder employeeBack(Integer userId, String orderNum) {
        TOrder tOrder = tOrderMapper.selectById(orderNum);
        if (tOrder.getEmployId()!=userId.longValue()){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_NO_ORDER);
        }
        //client修改为12待入库
        AddHandelForm addHandelForm = new AddHandelForm(null, 12, userId, orderNum, null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
        //client生成审核表
        Result<?> add1 = depotClient.add(orderNum);
        if (add1.getCode()!=200){
            throw new OrderException(add1.getCode(),add1.getMessage());
        }

        return tOrder;
    }

    /**
     * 根据状态分页查询员工订单
     * @param toBean 状态码 页码 每页个数
     * @param userId 员工token
     * @return 订单page对象
     */
    @Override
    public Page<TOrder> findStateOrder(Integer userId, FindStateOrderParam toBean) {
        if (toBean.getPageSize()==null){
            toBean.setPageSize(3);
        }
        if (toBean.getPageNum()==null){
            toBean.setPageNum(1);
        }
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("employ_id",userId);
        wrapper.eq("state",toBean.getStateId());
        Page<TOrder> tOrderPage = new Page<>(toBean.getPageNum(), toBean.getPageSize());
        tOrderMapper.selectPage(tOrderPage,wrapper);
        return tOrderPage;
    }



    /**
     * 根据站点id查询该站点所属所有订单
     * id 站点id
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public Page<TOrder> findByStationId(Integer id,Integer pageNum,Integer pageSize) {
        Result<Station> result = stationClient.byId(id);
        if (result.getCode()!=200){
            throw new RebornException(result.getMessage(),result.getCode());
        }
        pageNum = pageNum==null?1:pageNum;
        pageSize = pageSize==null?3:pageSize;
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id",id);
        Page<TOrder> tOrderPage = new Page<>(pageNum, pageSize);
        return tOrderMapper.selectPage(tOrderPage, wrapper);
    }

    /**
     * 根据站点id查询该站点所有待站点审批订单
     * id 站点id
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public Page<TOrder> findUnHandelByStationId(Integer id,Integer pageNum,Integer pageSize) {
        Result<Station> result = stationClient.byId(id);
        if (result.getCode()!=200){
            throw new RebornException(result.getMessage(),result.getCode());
        }
        pageNum = pageNum==null?1:pageNum;
        pageSize = pageSize==null?3:pageSize;

        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id",id);
        List<TOrder> tOrders = tOrderMapper.selectList(wrapper);

        List<String> usefulOrderNum = new ArrayList<String>();
        if (tOrders!=null&&!tOrders.isEmpty()){
            //遍历每一个订单 查询订单状态为待审核的订单
            for (TOrder tOrder : tOrders) {
                String orderNum = tOrder.getId();//订单号
                //调用flowclient 查看当前的订单走到哪一步了   是否有flow_code==6(待站点确认)且now==1(待站点确认为当前状态)
                Result<FlowHandle> flowHandleResult = flowClient.locationConfirm(orderNum);
                if (flowHandleResult.getCode()!=200){
                    throw new RebornException(flowHandleResult.getMessage(),flowHandleResult.getCode());
                }
                FlowHandle flowHandle = flowHandleResult.getData();
                if (flowHandle.getFlowCode()==6 && flowHandle.getNow()==1){
                    //满足条件的订单塞进集合
                    usefulOrderNum.add(tOrder.getId());
                }
            }
        }
        if (!usefulOrderNum.isEmpty()){
            //进行查询返回
            QueryWrapper<TOrder> wrapper1 = new QueryWrapper<>();
            wrapper1.in("id",usefulOrderNum);
            Page<TOrder> page = new Page<>(pageNum, pageSize);
            Page<TOrder> page1 = tOrderMapper.selectPage(page, wrapper1);
            return page1;
        }
        throw new RebornException("该站点没有待审核订单",50001);
    }

    /**
     * 根据站点id查询该站点所有待分配员工订单
     * id 站点id
     */
    @Override
    public Page<TOrder> findUnAssByStationId(Integer id, Integer pageNum, Integer pageSize) {
        Result<Station> result = stationClient.byId(id);
        if (result.getCode()!=200){
            throw new RebornException(result.getMessage(),result.getCode());
        }
        pageNum = pageNum==null?1:pageNum;
        pageSize = pageSize==null?3:pageSize;

        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id",id);
        List<TOrder> tOrders = tOrderMapper.selectList(wrapper);

        List<String> usefulOrderNum = new ArrayList<String>();
        if (tOrders!=null&&!tOrders.isEmpty()){
            //遍历每一个订单 查询订单状态为待审核的订单
            for (TOrder tOrder : tOrders) {
                if (tOrder.getEmployId()==null||tOrder.getEmployId()==0){
                    usefulOrderNum.add(tOrder.getId());
                }
            }
        }
        if (!usefulOrderNum.isEmpty()){
            //进行查询返回
            QueryWrapper<TOrder> wrapper1 = new QueryWrapper<>();
            wrapper1.in("id",usefulOrderNum);
            Page<TOrder> page = new Page<>(pageNum, pageSize);
            tOrderMapper.selectPage(page, wrapper1);
            System.out.println(JSONUtil.toJsonStr(page.getRecords()));
            List<TOrder> list = page.getRecords();
            for (TOrder record : list) {
                String typeId = record.getTypeId();
                System.out.println(typeId);
                // 移除方括号和空格
                typeId = typeId.trim().replace("[", "").replace("]", "");

                // 分割字符串并将其转换为List<Integer>
                String[] stringArray = typeId.split(",");
                List<Integer> list1 = new ArrayList<>();
                for (String s : stringArray) {
                    // 转换为整数并添加到列表
                    list1.add(Integer.parseInt(s.trim()));
                }
                Result<List<JunkType>> byIdList = depotClient.getByIdList(list1);
                if (byIdList.getCode()!=200){
                    throw new OrderException(byIdList.getCode(),byIdList.getMessage());
                }
                String s = null;
                for (JunkType datum : byIdList.getData()) {
                    if (s!=null){
                        s=s+","+datum.getTypeName();
                    }
                    if (s==null){
                        s=datum.getTypeName();
                    }
                }
                record.setTypeId(s);

            }

            page.setRecords(list);

            return page;
        }
        throw new RebornException("该站点没有待分配员工的订单",50001);
    }

    @Override
    public TOrder insetOrders(Integer userId, AddBookingOrdersparam toBean) {
        //判断用户是否存在
        Result<TUser> tUserResult = userClient.userById(userId.longValue());
        if (tUserResult.getCode()!=200){
            throw new AccountException(tUserResult.getCode(),tUserResult.getMessage());
        }
//        //验证实名状态
//        if (tUserResult.getData().getRealNameState()!=0){
//            throw new AccountException(AccountExceptionCode.ACCOUNT_NOT_ID);
//        }
        //判断用户信誉分

        //判断用户地址合法性
        Long aLong = Long.valueOf(toBean.getAddressId());
        Result<UserAddrees> addressResult = userClient.addressById(aLong.longValue());
        if (addressResult.getCode()!=200){
            throw new AccountException(addressResult.getCode(),addressResult.getMessage());
        }
        if (addressResult.getData().getState()!=0){
            throw new AccountException(AccountExceptionCode.ACCOUNT_NO_ACCOUNT_NO_ADDRESS);
        }
        //判断预约时间是否合适
        Date date = new Date();
        long time = date.getTime();
        long time1 = DateUtil.stringConversionDate(toBean.getBookingTime()).getTime();
        if (time1<time){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_ACCOUNT);
        }
        //地理/逆地理编码
        Map lonAndLat = GaudMapUtil.getLonAndLat(addressResult.getData().getUserAddress(),"727abe621f3273de0e8a4b0a8fa8b3be");
        //经度
        String lng = lonAndLat.get("lng").toString();
        //维度
        String lat = lonAndLat.get("lat").toString();
        //判断废品类别是否存在返回最近站点
        Set<Integer> ids = toBean.getTypeId().stream().collect(Collectors.toSet());
        System.out.println(LocalDateTime.now());
        System.out.println(DateUtil.stringConversionLocalDate(toBean.getBookingTime()));
        System.out.println("=====================================");
        FindByLocationAndJunkForm junkForm = new FindByLocationAndJunkForm(ids, Double.valueOf(lng), Double.valueOf(lat), toBean.getBookingTime());
        Result<Station> junk = stationClient.findByLocationAndJunk(junkForm);
        System.out.println(JSONUtil.toJsonStr(junk));
        if (junk.getCode()!=200){
            throw new AccountException(junk.getCode(),junk.getMessage());
        }



        String orderNum = new Snowflake(1, 1).nextIdStr();//押金订单编号
        //修改新订单空数据
        TOrder tOrder = new TOrder();
        tOrder.setImg(toBean.getImg());
        tOrder.setTypeId(JSONUtil.toJsonStr(toBean.getTypeId()));
        tOrder.setExpectWeight(toBean.getExpectWeight());
        tOrder.setId(orderNum);
        tOrder.setPhone(addressResult.getData().getPhone());
        tOrder.setState((long)1);
        tOrder.setUserId((long)userId);
        tOrder.setCreateTime(LocalDateTime.now().toString());
        tOrder.setBookingTime(DateUtil.stringConversionLocalDate(toBean.getBookingTime()).toString());
        tOrder.setAddress(addressResult.getData().getUserAddress());
        tOrder.setAddressId(Long.valueOf(toBean.getAddressId()));
        tOrder.setName(addressResult.getData().getUserAddress());
        tOrder.setStationId(junk.getData().getId().longValue());
        tOrderMapper.insert(tOrder);

        //根据站点查询站长
//        employeeClient.
        //client新增 订单流程  1已下单
        AddHandelForm addHandelForm = new AddHandelForm(1, 1, userId, orderNum, "用户已下单");
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }
        return tOrder;

    }

    @Override
    public TOrder translationPay(Integer userId, String orderNum) throws Exception {
        TOrder tOrder = tOrderMapper.selectById(orderNum);

        if (tOrder==null){
            throw new OrderException(OrderExceptionCode.ORDER_EXCEPTION_CODE_NO_ORDER);
        }
        //查询押金订单
        QueryWrapper<TDownpayment> wrapper = new QueryWrapper<>();
        wrapper.eq("order_num",orderNum);
        TDownpayment tDownpayment = downpaymentMapper.selectOne(wrapper);
        if (tDownpayment!=null){
            tOrder.setTotalPrice(tOrder.getTotalPrice().add(new BigDecimal(20)));
        }

        Result<TUser> tUserResult = userClient.byAliPayUsername(tOrder.getUserId());
        if (tUserResult.getCode()!=200){
            throw new OrderException(tUserResult.getCode(),tUserResult.getMessage());
        }

        //查询用户信息
        String s = null;
        try {
            s = alipay.transferPay(orderNum, tOrder.getTotalPrice().toString(), tUserResult.getData().getAlipayAccount(), tUserResult.getData().getAlipayUsername());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        //client修改为12待入库
        AddHandelForm addHandelForm = new AddHandelForm(null, 12, userId, orderNum, null);
        Result<FlowHandle> add = flowClient.add(addHandelForm);
        if (add.getCode()!=200){
            throw new OrderException(add.getCode(),add.getMessage());
        }

        tOrder.setState(12L);
        tOrderMapper.updateById(tOrder);
        //用户加信誉分
        AddCredibilityForm credibilityForm = new AddCredibilityForm(tOrder.getUserId(), (long) 10);
        Result<TUser> tUserResult1 = userClient.addCredibility(credibilityForm);
        if (tUserResult1.getCode()!=200){
            throw new AccountException(tUserResult.getCode(),tUserResult.getMessage());
        }
        return tOrder;
    }


    /**
     * 根据账号id返回订单集合
     * @param id 账号id
     * @return
     */
    @Override
    public List<TOrder> findOrderByAccountId(Integer id) {
        List<TOrder> orders = tOrderMapper.selectList(new QueryWrapper<TOrder>().eq("user_id", id));
        return orders;
    }


}
